package com.yydream.common.handler;

import com.alibaba.fastjson2.JSON;
import com.yydream.common.constant.HttpStatus;
import com.yydream.common.utils.R;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Administrator
 * @file Spring-Security-Tutorial
 * @create 2020 09 28 14:37
 */
@Component
public class CustomAccessDeniedHandler implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        R error = R.error(HttpStatus.INVALID_TOKEN.getCode(), HttpStatus.INVALID_TOKEN.getMsg());
        httpServletResponse.setContentType("application/json;charset=utf-8;");
        httpServletResponse.setStatus(200);
        httpServletResponse.getWriter().write(JSON.toJSONString(error));
    }
}